import popupInfo from "../../components/popupInfo.js";
import {
    addRegister,
    getAllRegister,
    getDepartmentsFromHospitalId,
    getHospitalFromId,
    getLoginUser
} from "../utils/common_network.js";

import {dayOfWeek, formatMonthAndDay} from "../../date_utils.js"
import {exist} from "../../utils.js";
import {ResultCode} from "../../network.js";
import squareButton from "../../components/squareButton.js";

export default {
    components: {
        'popup-info': popupInfo,
        'square-button': squareButton
    },
    props: {
        id: String
    },
    setup(props) {
        const popup = Vue.ref(null);
        const user = Vue.ref({name: "姓名"});
        const router = VueRouter.useRouter();
        const route = VueRouter.useRoute();
        const hospital = Vue.ref({
            name: "医院名称", address: "医院地址"
        });
        const _departments = Vue.ref([{id: 0}]);
        const selectedDepartmentIndex = Vue.ref(0);
        const registerMap = Vue.ref({});
        const noSearchResult = Vue.ref(false);
        const departments = Vue.computed({
            get() {
                selectedDepartmentIndex.value = 0;
                // if (searchDp.value === "") {
                //     noSearchResult.value = false;
                //     return _departments;
                // }
                const r = _departments.value.filter(v => {
                    const name = v['name'];
                    if (exist(name)) {
                        return name.includes(searchDp.value);
                    }
                });
                // console.log(r);
                if (r.length === 0) {
                    noSearchResult.value = true;
                    return _departments.value;
                }
                noSearchResult.value = false;
                return r;
            }
        });
        const selectedDpid = Vue.computed({
            get() {
                // console.log(departments.value);
                // console.log(selectedDepartmentIndex.value);
                const selectedDp = departments.value[selectedDepartmentIndex.value];
                if (exist(selectedDp)) {
                    return selectedDp.id;
                }
            }
        });

        const searchDp = Vue.ref("");

        function getSelectedDepartmentStyle(index) {
            if (index === selectedDepartmentIndex.value) {
                // console.log('selected index: ' + index);
                return {
                    'background': '#5DC3F8FF'
                }
            }
            return {};
        }

        function onDepartmentClick(index) {
            selectedDepartmentIndex.value = index;
            selectRIndex.value = 0;
            selectDoctorId.value =
                Object.values(registerMap.value[selectedDpid.value]
                    [selectedDateIndex.value]['detailsMap'])[0]['doctorId'];
        }

        const mainTitle = Vue.ref(null);
        Vue.onBeforeUnmount(() => {
            window.removeEventListener('resize', contentResize);
        });

        function contentResize() {
            if (exist(mainTitle.value)) {
                // console.log('resize mainTitle');
                const height = mainTitle.value.clientHeight;
                mainTitle.value.style.lineHeight = height + "px";
            }
            const rDatePanelV = rDatePanel.value;
            const rTitlePanelV = rTitlePanel.value;
            const rContentV = rContent.value;
            const rPanelV = rPanel.value;
            if (exist(rContentV) && exist(rTitlePanelV) && exist(rDatePanelV)
                && exist(rPanelV)) {
                const h1 = rTitlePanelV.clientHeight
                    + parseFloat(rTitlePanelV.style.marginBottom.replace("px", ''))
                    + parseFloat(rTitlePanelV.style.marginTop.replace("px", ''));
                // console.log(h1);
                const h2 = rDatePanelV.clientHeight;
                // console.log(h2);
                const h = rPanelV.clientHeight;
                rContent.value.style.height = (h - h1 - h2) + 'px';
            }
        }

        window.addEventListener('resize', contentResize);

        function backToIndex() {
            router.push({path: '/'});
        }

        let refreshTimer = undefined;

        async function refreshData() {
            getLoginUser(popup, backToIndex, user);
            getHospitalFromId(props.id, hospital);
            //拿到科室id才能继续查
            await getDepartmentsFromHospitalId(props.id, _departments);
            // console.log(departments.value);
            for (let department of _departments.value) {
                // console.log(department);
                await getAllRegister(props.id, department.id,
                    registerMap);
                // console.log(registerMap);
            }
            // console.log(registerMap);
        }

        Vue.onMounted(async () => {
            await refreshData();
            contentResize();
            refreshTimer = setInterval(refreshData, 60000);
            selectDoctorId.value =
                Object.values(registerMap.value[selectedDpid.value]
                    [selectedDateIndex.value]['detailsMap'])[0]['doctorId'];
        })

        Vue.onBeforeUnmount(() => {
            if (exist(refreshTimer)) {
                clearInterval(refreshTimer);
            }
        })

        const selectedDateIndex = Vue.ref(0);

        function getSelectedDateStyle(index) {
            if (index === selectedDateIndex.value) {
                return {
                    'background': '#DEEDF9',
                    'border-radius': '15px'
                };
            }
            return {};
        }

        function onDateClick(index) {
            selectedDateIndex.value = index;
            selectDoctorId.value =
                Object.values(registerMap.value[selectedDpid.value]
                    [selectedDateIndex.value]['detailsMap'])[0]['doctorId'];
        }

        const rTitlePanel = Vue.ref(null);
        const rDatePanel = Vue.ref(null);
        const rContent = Vue.ref(null);
        const rPanel = Vue.ref(null);

        const registerInfoList = Vue.computed({
            get() {
                // console.log("get registerInfoList");
                const rInfo = registerMap.value[selectedDpid.value];
                // console.log(rInfo);
                if (exist(rInfo)) {
                    // console.log("end of get registerInfoList return value");
                    return rInfo[selectedDateIndex.value]['detailsMap'];
                }
                // console.log("end of get registerInfoList return []");
                return [];
            }
        });

        function registerRemain(i) {
            let result = 0;
            for (let o of i['remain']) {
                result += o;
            }
            return result;
        }

        const selectRIndex = Vue.ref(0);
        const nonExpertDoctorGroupId = "#";
        const selectDoctorId = Vue.ref(nonExpertDoctorGroupId);

        function onRClick(key, index) {
            selectDoctorId.value = key;
            selectRIndex.value = index;
        }

        function getRStyle(index) {
            if (index === selectRIndex.value) {
                const v = '3px solid #66BDD7';
                return {
                    'border-top': v,
                    'border-bottom': v,
                    'border-left': v,
                    'border-right': v,
                };
            }
            return {
                'border-top': '0',
                'border-bottom': '1px solid black',
                'border-left': '0',
                'border-right': '0',
            };
        }

        function onRegisterClick(index) {
            if (!haveRemain(index)) {
                return;
            }
            const rInfo = registerMap.value[selectedDpid.value];
            if (exist(rInfo)) {
                const dpInfo = rInfo[selectedDateIndex.value];
                popup.value.onConfirm = () => {
                    addRegister(selectDoctorId.value, user.value.id,
                        index, dpInfo['date'], departments.value[selectedDepartmentIndex.value].id,
                        props.id)
                        .then(r => {
                            if (r.data.code === ResultCode.SUCCESS) {
                                console.log("register success");
                                Vue.nextTick(async () => {
                                    popup.value.show("挂号成功！");
                                    await refreshData();
                                }).then();
                            }
                        });
                }
                popup.value.show("请您缴费后点击“我已缴费”");
                // console.log(dpInfo);
            }
        }

        function haveRemain(index) {
            const detailsMap = registerInfoList.value[selectDoctorId.value];
            if (exist(detailsMap)) {
                // console.log(detailsMap);
                const remain = detailsMap['remain'][index];
                // console.log(remain);
                if (remain > 0) {
                    return true;
                }
            }
            return false;
        }

        function registerStyle(index) {
            if (haveRemain(index)) {
                return {
                    'border': '1px solid black',
                    'color': 'black',
                    'cursor': 'pointer',
                }
            }
            return {
                'border': '1px solid grey',
                'color': 'grey',
                'cursor': 'default',
            }
        }

        function onBackClick() {
            popup.value.onConfirm = () => {
                router.go(-1);
            };
            popup.value.show("返回上一界面吗");
        }

        function onLittleTipClick() {
            popup.value.show("温馨提示内容", "温馨提示");
        }

        function onGotoRegisterInfoClick() {
            router.push({path: '/register_info/' + props.id});
        }

        function onHelpClick() {
            popup.value.show("指南内容", "预约指南");
        }

        function onShowDoctorWorkTimeClick() {
            router.push({path: '/work_info/' + props.id});
        }

        return {
            popup, user, route, router,
            hospital, mainTitle, selectedDpid,
            departments, getSelectedDepartmentStyle,
            selectedDepartmentIndex, onDepartmentClick,
            registerMap, formatMonthAndDay, dayOfWeek,
            getSelectedDateStyle, onDateClick,
            selectedDateIndex, rContent, rDatePanel, rTitlePanel,
            rPanel, registerInfoList, registerRemain,
            selectRIndex, onRClick, getRStyle, onRegisterClick,
            registerStyle, selectDoctorId, onBackClick,
            onGotoRegisterInfoClick, onHelpClick,
            onShowDoctorWorkTimeClick, onLittleTipClick,
            searchDp, noSearchResult
        }
    },
    template: `<div class="container-fluid" style="height: 100%;">
    <square-button background-url="/images/exit_images/exit2.svg"
                   :width-in-parent=6
                   right="4%"
                   bottom="4%"
                   :z-index="1031"
                   @onClick="onBackClick"
    ></square-button>
    <popup-info ref="popup"></popup-info>
    <div class="row" style="height: 100%; padding-left: 0; padding-right: 0;">
        <div style="padding-left: 0; padding-right: 0;height: 100%;
        background: linear-gradient(rgba(241,247,249,1) 66.412%,rgba(255,255,255,1) 100%);" 
        class="col-md-3">
            <div style="height: 100%; width: 100%; padding-left: 40px; padding-right: 40px;
             font-size: 24px; background: linear-gradient(rgba(241,247,249,1) 66.412%,
             rgba(255,255,255,1) 100%);">
                <div style="width: 100%;text-align: center;font-size: 24px;
                    padding-top: 10%;padding-bottom: 10%;" class="my-font">
                    姓名:{{user.name}}
                </div>
                <input type="text" style="width: 100%; border-radius: 15px; 
                padding-left: 10px; padding-right: 10px;margin-top: 10%;"
                placeholder="搜索科室名" v-model="searchDp">
                <div style="font-size: 18px;text-align: center;" class="my-font" v-show="noSearchResult">
                    暂无搜索结果，为您显示全部科室
                </div>
                <div style="padding-top: 20%;">
                    <div style="font-size: 24px;" class="my-font">科室选择
                        <img src="/images/user_main/navigation.png" style="height: 50px;">
                    </div>
                    <table style="padding-left: 20px;">
                        <tr style="font-size: 20px;margin: 20px 40px 20px 20px;
                        border-radius: 10px;cursor: pointer;display: block;
                        padding-right: 10px" class="my-font" :style="getSelectedDepartmentStyle(index)"
                            v-for="(item, index) in departments" @click="onDepartmentClick(index)">
                            ·{{item.name}}
                        </tr>
                    </table>
                </div>
            </div>
            <div style="height: 70px;position: absolute;bottom: 20px;width: 100%;text-align: center;
            font-size: 20px;">
                <div style="height: 50%;cursor: pointer;"
                    @click="onGotoRegisterInfoClick()">
                    <span style="font-size: 26px;">|</span>
                    <span class="my-font">挂号信息查看</span>
                    <span style="font-size: 26px;">|</span>
                </div>
                <div style="height: 50%;">
                    <span style="font-size: 26px;">|</span>
                    <span style="cursor: pointer;" class="my-font" @click="onHelpClick()">
                        预约指南
                    </span>
                    <span style="font-size: 26px;">|</span>
                    <span style="cursor: pointer;" class="my-font" @click="onShowDoctorWorkTimeClick()">
                        门诊排班
                    </span>
                    <span style="font-size: 26px;">|</span>
                    <span style="cursor: pointer;" class="my-font" @click="onLittleTipClick()">
                        温馨提示
                    </span>
                    <span style="font-size: 26px;">|</span>
                </div>
            </div>
        </div>
        <div style="padding-left: 0; padding-right: 0; height: 100%;" class="col-md-9">
            <div class="row" style="height: 20%; text-align: center;
                margin: 0;" ref="mainTitle">
                <div class="col-md-4" style="font-size: 28px;display: inline-block;">
                    <span class="my-font">
                        {{hospital.name}}&nbsp;
                    </span>
                    <span style="font-size: 50px;">|</span>
                </div>
                <div class="col-md-4 my-font" style="font-size: 40px;">
                    预约挂号
                </div>
                <div class="col-md-4" style="font-size: 40px;"></div>
            </div>
            <div style="height: 80%; padding-top: 5%;background: linear-gradient(rgba(176,216,221,1) 0%,rgba(255,255,255,1) 100%);">
                <div ref="rPanel" 
                style="margin-left: 10%; margin-right: 10%; height: 80%; background-color: #ffffff; border-top-left-radius: 30px; border-top-right-radius: 30px; border: 1px solid;">
<!--                    <div class="row" style="height: 60px; margin-left: 0; margin-right: 0; border-bottom: 1px solid;">-->
<!--                        <div class="col-md-6 my-font"-->
<!--                             style="font-size: 24px; text-align: center; line-height: 60px; border-right: 1px solid;">-->
<!--                            按日期-->
<!--                        </div>-->
<!--                        <div class="col-md-6 my-font" -->
<!--                            style="font-size: 24px; text-align: center;line-height:60px">-->
<!--                            按医生-->
<!--                        </div>-->
<!--                    </div>-->
                    <div ref="rTitlePanel" style="height: 40px; margin-left: 15px;
                     margin-top: 15px; margin-bottom: 15px; 
                     border-left: 5px solid rgb(100, 139, 224); 
                     font-size: 20px; line-height: 40px; 
                     text-indent: 1em; color: #648BE0FF;" class="my-font">
                        日期选择
                    </div>
                    <div ref="rDatePanel" style="height: 60px;">
                        <table style="width: 80%; height: 100%; margin-left: 10%;">
                            <tbody>
                            <tr>
                                <td style="text-align: center;font-size: 18px;
                                color: #648BE0FF;cursor: pointer;" class="my-font"
                                :style="getSelectedDateStyle(index)"
                                @click="onDateClick(index)"
                                 v-for="(item, index) in registerMap[selectedDpid]">
                                    {{dayOfWeek(item.date)}}<br>{{formatMonthAndDay(item.date)}}
<!--                                    {{item}}-->
                                 </td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                    <div ref="rContent"
                        style="margin-left: 0;margin-right: 0;padding-top: 10px;
                        padding-bottom: 15px;" class="row">
                        <div style="border-right: 1px solid black;height: 100%;
                        overflow-y: auto;" class="col-md-6">
                            <div style="margin-left: 0;margin-right: 0;height: 70px;
                            padding-left: 15px;padding-top: 10px;padding-bottom: 10px;
                            cursor: pointer;"
                            v-for="(item, key, index) in registerInfoList"
                            :style="getRStyle(index)"
                            @click="onRClick(key, index)"
                            class="row">
                                <div style="height: 100%;padding: 0;" class="col-md-2">
                                    <img style="height: 100%;"
                                     src="/images/register/register_button.png" alt="">
                                </div>
                                <div style="height: 100%;padding: 0;text-align: center;
                                font-size: 18px;" class="col-md-6 my-font">
                                    {{item['doctorName']}}<br>剩余号源:{{registerRemain(item)}}
                                </div>
                                <div style="height: 100%;padding: 0;font-size: 16px;
                                text-align: center;" 
                                class="col-md-4 my-font">
                                    <div style="height: 50%;">
                                        ￥{{item['price']}}
                                    </div>
                                    <div style="height: 50%;border-radius: 10px;
                                    border: 1px solid black">
                                        立即挂号
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div style="height: 100%;padding: 0;" 
                        class="col-md-6 my-font">
                            <table style="width: 100%;">
                                <tr style="width: 100%;height: 60px;">
                                    <td>
                                        <div style="width: 80%;text-align: center;
                                        height: 50px;line-height: 50px;vertical-align: center;
                                        border-radius: 15px;margin: 10%;"
                                        :style="registerStyle(0)"
                                        @click="onRegisterClick(0)">
                                            8:00 - 10:00
                                        </div>
                                    </td>
                                    <td>
                                        <div style="width: 80%;text-align: center;
                                        height: 50px;line-height: 50px;vertical-align: center;
                                        border-radius: 15px;margin: 10%;"
                                        :style="registerStyle(1)"
                                        @click="onRegisterClick(1)">
                                            10:00 - 12:00
                                        </div>
                                    </td>
                                </tr>
                                <tr style="width: 100%;height: 60px;">
                                    <td>
                                        <div style="width: 80%;text-align: center;
                                        height: 50px;line-height: 50px;vertical-align: center;
                                        border-radius: 15px;margin: 10%;"
                                        :style="registerStyle(2)"
                                        @click="onRegisterClick(2)">
                                            13:00 - 15:00
                                        </div>
                                    </td>
                                    <td>
                                        <div style="width: 80%;text-align: center;
                                        height: 50px;line-height: 50px;vertical-align: center;
                                        border-radius: 15px;margin: 10%;"
                                        :style="registerStyle(3)"
                                        @click="onRegisterClick(3)">
                                            15:00 - 17:00
                                        </div>
                                    </td>
                                </tr>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>`,
}